package com.leyou.user.service;

import com.leyou.goods.client.BrandClient;
import com.leyou.goods.client.CategoryClient;
import com.leyou.goods.client.GoodsClient;
import com.leyou.goods.client.SpecificationClient;
import com.leyou.item.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class GoodsService {
    //    注意区分接口中定义了可供外使用的方法，客户端中没有仅仅是对接口的调用，C->I->真正的Service方法
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private SpecificationClient specificationClient;

    /* 一次性封装所有查询数据 */
    public Map<String, Object> loadData(Long spuId) {
        Map<String, Object> spuMap = new HashMap<>();

        // 根据spuID查询spu
        Spu spu = this.goodsClient.querySpuById(spuId);
        spuMap.put("spu", spu);

        // 查询分类
        List<Long> cids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
        List<String> names = this.categoryClient.queryNamesByIds(cids);
        List<Map<String, Object>> categories = new ArrayList<>();
        for (int i = 0; i < cids.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", cids.get(i));
            map.put("name", names.get(i));
            categories.add(map);
        }

        spuMap.put("categories", categories);

        // 查询sku集合
        List<Sku> skus = this.goodsClient.querySkusBySpuId(spuId);
        spuMap.put("skus", skus);
       /* for (Sku sku : skus) {
            System.out.println("sku:"+sku.getTitle()+sku.getPrice());
        }*/

        // 品牌
        Brand brand = this.brandClient.queryBrandById(spu.getBrandId());
        spuMap.put("brand", brand);


        // cid3查询规格参数组
        List<SpecGroup> groups = this.specificationClient.queryGroupsWithParam(spu.getCid3());
        spuMap.put("groups", groups);

        // 查询特殊规格参数
        List<SpecParam> params = this.specificationClient.queryParams(null, spu.getCid3(), null, null);
        Map<Long, Object> paramMap = new HashMap<>();
        params.forEach(param -> {
            paramMap.put(param.getId(), param.getName());
        });
        spuMap.put("paramMap", paramMap);

        // 封装spuDetail
        SpuDetail spuDetail = this.goodsClient.querySpuDetailBySpuId(spuId);
        spuMap.put("spuDetail", spuDetail);
        //所有数据
//       232.html测试加入数据
        return spuMap;
    }


}
